#include "TcpServer.h"

TcpServer::TcpServer(const uint16_t port)
{
    acceptor_ = new Acceptor(&loop_, port);
    acceptor_->setnewConnectionCb(std::bind(&TcpServer::newconnection, this, std::placeholders::_1));
}
TcpServer::~TcpServer()
{
    delete acceptor_;
    for (auto &e : conns_)
    {
        delete e.second;
    }
}

void TcpServer::start()
{
    loop_.run();
}

void TcpServer::newconnection(Sock *clientSock)
{
    Connection *conn = new Connection(&loop_, clientSock);
    conn->setCloseCallBack(std::bind(&TcpServer::closecallback, this, std::placeholders::_1));
    conn->setErrorCallBack(std::bind(&TcpServer::errorcallback, this, std::placeholders::_1));
    printf("new connection(fd=%d,ip=%s,port=%d) ok.\n", conn->getFd(), conn->getIp().c_str(), conn->getPort());
    conns_[conn->getFd()] = conn;
}

void TcpServer::closecallback(Connection *conn)
{
    printf("client(eventfd=%d) disconnected.\n", conn->getFd());
    // close(getFd()); // 关闭客户端的fd。
    conns_.erase(conn->getFd());   // 从map中删除conn。
    delete conn;
}
void TcpServer::errorcallback(Connection *conn)
{
    printf("client(eventfd=%d) error.\n", conn->getFd());
    // close(getFd()); // 关闭客户端的fd。
    conns_.erase(conn->getFd());   // 从map中删除conn。
    delete conn;
}
